<template>
  <div class="minapplets">
    <div class="outmain ba_f formwidth">
      <div class="shuju_title mar_b20">
        <div class="shuju_title_text">
          <span>小程序设置</span>
        </div>
      </div>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="基础设置" name="1">
          <el-form ref="form" :model="form" :rules="rules" label-width="180px" class="mar_t20">
            <el-form-item label="当前小程序uniacid">
              <el-input v-model="form.uniacid" disabled></el-input>
            </el-form-item>
            <el-form-item label="小程序名称" prop="name" :required="true">
              <el-input v-model="form.name" placeholder="请输入小程序名称"></el-input>
            </el-form-item>
            <el-form-item label="原始ID" prop="originalAppId" :required="true">
              <el-input v-model="form.originalAppId" placeholder="请输入小程序原始ID"></el-input>
              <div class="yb_margin lh16">获取方式：微信公众平台-设置-账号信息-原始ID</div>
            </el-form-item>
            <el-form-item label="AppID(小程序ID)" prop="appId" :required="true">
              <el-input v-model="form.appId" placeholder="请输入小程序AppID"></el-input>
              <div class="yb_margin lh16">获取方式：微信公众平台-开发-开发设置-开发者ID-小程序AppID</div>
            </el-form-item>
            <el-form-item label="AppSecret(小程序密钥)" prop="appSecret" :required="true">
              <el-input v-model="form.appSecret" placeholder="请输入小程序AppSecret" :type="passw">
                <i slot="suffix" :class="icon" @click="showPass"></i>
              </el-input>
              <div class="yb_margin lh16">获取方式：微信公众平台-开发-开发设置-开发者ID-小程序AppSecret</div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <!--          <el-tab-pane label="支付设置" name="2">-->
        <!--              <el-form ref="form" :model="form" label-width="180px" class="mar_t20">-->
        <!--                  <div class="maintitle">微信支付设置</div>-->
        <!--                  <el-form-item label="微信支付">-->
        <!--                      <div>在「小程序后台 - 微信支付」页面下申请开通并完成相关配置。 完成后，请在本页填写你的商户号和商户密钥。</div>-->
        <!--                  </el-form-item>-->
        <!--                  <el-form-item label="商户号">-->
        <!--                      <el-input v-model="form.name"></el-input>-->
        <!--                  </el-form-item>-->
        <!--                  <el-form-item label="商户秘钥" >-->
        <!--                      <el-input v-model="form.name"></el-input>-->
        <!--                  </el-form-item>-->
        <!--                  <el-form-item>-->
        <!--                      &lt;!&ndash;              <el-button type="primary" @click="onSubmit">立即创建</el-button>&ndash;&gt;-->
        <!--                      <el-button>去修改</el-button>-->
        <!--                  </el-form-item>-->
        <!--                  <div class="maintitle">微信退款设置</div>-->
        <!--                  <el-form-item label="微信退款">-->
        <!--                      <div>目前小程序只支持微信自有支付，你可以在「微信支付商户平台」下载证书，上传文件类型限.pem文件</div>-->
        <!--                  </el-form-item>-->
        <!--                  <el-form-item label="退款证书cert">-->
        <!--                      <div class="subjectcolor2">未上传</div>-->
        <!--                  </el-form-item>-->
        <!--                  <el-form-item label="退款证书key" >-->
        <!--                      <div class="subjectcolor2">已上传</div>-->
        <!--                  </el-form-item>-->
        <!--                  <el-form-item>-->
        <!--                      <el-button>去修改</el-button>-->
        <!--                  </el-form-item>-->
        <!--              </el-form>-->
        <!--          </el-tab-pane>-->
        <el-tab-pane label="模板消息" name="2">
          <div class="ba_f8 mar_20 pad_20">
            <el-button type="primary" size="medium" @click="yjdy">一键获取订阅消息</el-button>
            <div class="lh25 mar_t10 msgtext fon_12">
              温馨提示：1.获取前请先确认您已获得订阅消息的实用权限，并且订阅消息中没有任何数据。获取后请不要到微信小程序后台 删除相应的订阅消息，否则会影响订阅消息正常使用。
              <br />2.请在小程序后台添加"商家自营 > 家电/数码/手机 ;生活服务 > 百货/超市/便利店; 生活服务 > 休闲娱乐
            </div>
          </div>
          <el-form ref="form2Data" :model="form2Data" label-width="180px" class="mar_t20">
            <el-form-item label="下单成功通知" :required="true">
              <el-input v-model="form2Data.payOkTid" placeholder="请输入模板ID"></el-input>
              <!--                            <el-button class="mar_l20" v-popover:popover2>查看订阅消息示例</el-button>-->
              <!--                            <el-popover ref="popover2" placement="top-start" title="订单拒绝接单通知" width="250"-->
              <!--                                        trigger="hover">-->
              <!--                                <div class="orderpop fon_12">-->
              <!--                                    <p>您的订单被拒绝接单</p>-->
              <!--                                    <p>订单金额：45.22</p>-->
              <!--                                    <p>订单名称：确认您已获得模板消息</p>-->
              <!--                                    <p>下单时间：2019-08-24 11:45:14</p>-->
              <!--                                    <p>订单状态：已拒单</p>-->
              <!--                                </div>-->
              <!--                            </el-popover>-->
            </el-form-item>
            <el-form-item label="订单自提通知" :required="true">
              <el-input v-model="form2Data.takeTid" placeholder="请输入模板ID"></el-input>
            </el-form-item>
            <el-form-item label="商家拒单通知" :required="true">
              <el-input v-model="form2Data.refuseTid" placeholder="请输入模板ID"></el-input>
            </el-form-item>
            <el-form-item label="商家接单通知" :required="true">
              <el-input v-model="form2Data.acceptTid" placeholder="请输入模板ID"></el-input>
            </el-form-item>
            <el-form-item label="订单配送通知" :required="true">
              <el-input v-model="form2Data.deliveryTid" placeholder="请输入模板ID"></el-input>
            </el-form-item>
            <!--                        <el-form-item label="申请退款通知" :required="true">-->
            <!--                            <el-input v-model="form2.name" placeholder="请输入模板ID"></el-input>-->
            <!--                            <el-button class="mar_l20">查看订阅消息示例</el-button>-->
            <!--                        </el-form-item>-->
            <el-form-item label="订单退款通知" :required="true">
              <el-input v-model="form2Data.refundResultTid" placeholder="请输入模板ID"></el-input>
              <!--                            <el-button class="mar_l20">查看订阅消息示例</el-button>-->
            </el-form-item>
            <el-form-item label="快餐订单提醒通知" :required="true">
              <el-input v-model="form2Data.fastTakeTid" placeholder="请输入模板ID"></el-input>
            </el-form-item>
            <el-form-item label="堂食接单通知" :required="true">
              <el-input v-model="form2Data.inOrderTid" placeholder="请输入模板ID"></el-input>
            </el-form-item>
            <el-form-item label="当面付支付成功通知" :required="true">
              <el-input v-model="form2Data.cashierTid" placeholder="请输入模板ID"></el-input>
            </el-form-item>
            <el-form-item label="排队到号通知" :required="true">
              <el-input v-model="form2Data.queuingTid" placeholder="请输入模板ID"></el-input>
            </el-form-item>
            <!--                        <el-form-item label="充值成功通知" :required="true">-->
            <!--                            <el-input v-model="form2.name" placeholder="请输入模板ID"></el-input>-->
            <!--                            <el-button class="mar_l20">查看订阅消息示例</el-button>-->
            <!--                        </el-form-item>-->
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="页面路径" name="3">
          <el-table v-loading="listLoading" :element-loading-text="elementLoadingText" :data="list" class="mar_t20" style="width: 100%">
            <el-table-column prop="name" label="名称"></el-table-column>
            <el-table-column prop="page" label="链接"></el-table-column>
            <el-table-column prop="address" label="操作" width="380">
              <template slot-scope="scope">
                <div class="flex">
                  <el-button size="mini" @click="copyText(scope.row)">复制链接</el-button>
                  <el-button size="mini" type="primary" plain @click="codeSee(scope.row)">查看二维码</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <!--                    <el-pagination-->
          <!--                            background-->
          <!--                            layout="prev, pager, next"-->
          <!--                            :total="page.total"-->
          <!--                            :page-size="page.pagesize"-->
          <!--                            :current-page.sync='page.currentPage'-->
          <!--                            @current-change="handleCurrentChange">-->
          <!--                    </el-pagination>-->
        </el-tab-pane>
        <el-tab-pane label="上传小程序" name="4" v-if="data==2">
          <el-form ref="form3" :model="form3" label-width="180px" class="mar_t20" v-show="shawCode=='1'">
            <el-form-item label="版本号">
              <el-input v-model="form3.version" placeholder="请输入版本号" :required="true"></el-input>
            </el-form-item>
            <el-form-item label="版本描述" prop="name">
              <el-input v-model="form3.describe" placeholder="请输入版本描述" :required="true" type="textarea" rows="6"></el-input>
            </el-form-item>
            <el-form-item label="插件选择">
              <el-checkbox-group v-model="plugin">
                <el-checkbox label="live">小程序直播</el-checkbox>
              </el-checkbox-group>
              <div class="yb_margin lh16">如当前小程序未开通直播功能请勿勾选</div>
            </el-form-item>
          </el-form>
          <div class="shawCode t_c pad_30" v-show="shawCode=='2'">
            <img v-show="code==2" :src="loginImg" class="imgCode" />
            <div v-show="code==1" class="pad_20">
              <img src="../../assets/img/setting/wxupload-wait.png" class="loadWait" />
            </div>
            <div v-show="code==1" class="mar_b20">正在获取二维码,请耐心等待,等待时间大约</div>
            <div v-show="code==1" class="mar_t20 waitTime">{{ initTimer }}s</div>
            <div v-show="code==2" class="mar_b20">请扫描二维码，确认后将直接上传代码</div>
            <div v-show="code==3" class="mar_b20">
              <div class="mar_b20">扫描成功,等待上传代码,请稍后...</div>
              <img src="../../assets/img/setting/wxupload-wait.png" class="loadWait" />
              <div class="waitTime mar_t20">{{ updateTimes }}s</div>
            </div>
            <div v-show="code==4">上传代码成功，请到微信开发平台小程序后台预览，提交审核应用。</div>
            <div v-show="code==4">
              微信开发平台小程序后台
              <a href="https://mp.weixin.qq.com/" target="_blank">https://mp.weixin.qq.com/</a>
            </div>
            <img v-show="code==4" :src="previewImg" class="imgCode" />
          </div>
        </el-tab-pane>
      </el-tabs>
      <el-dialog title="二维码" :visible.sync="dialogVisible" :close-on-click-modal="false" width="30%">
        <div class="t_c">
          <img :src="codeImg" class="wid imgCode" />
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false" size="medium">取 消</el-button>
          <el-button type="primary" @click="dialogVisible = false" size="medium">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="mar_t20 ba_f pad_20 t_c" v-show="activeName!='3' && activeName!='4'">
      <el-button type="primary" @click="onSubmit">保存</el-button>
    </div>
    <div class="mar_t20 ba_f pad_20 t_c" v-show="activeName=='4' && code==1">
      <el-button type="primary" @click="upload">确认并上传</el-button>
    </div>
  </div>
</template>
<script>
import { getConfig, postConfig, getPage, getMiniTemplates, getCode, getEdition, getLoginCode, getLoginStatus, preview } from '@/api/setup';

export default {
  created() {
    this.init();
    this.getEdition();
  },
  data() {
    return {
      activeName: '1',
      form: {
        uniacid: '',
        name: '',
        appId: '',
        appSecret: '',
        originalAppId: ''
      },
      form2Data: {
        payOkTid: '',
        refuseTid: '',
        acceptTid: '',
        refundResultTid: '',
        takeTid: '',
        deliveryTid: '',
        fastTakeTid: '',
        inOrderTid: '',
        cashierTid: '',
        queuingTid: '',
      },
      rules: {
        name: [{ required: true, message: '请输入小程序名称', trigger: 'blur' }],
        originalAppId: [{ required: true, message: '请输入originalAppId', trigger: 'blur' }],
        appId: [{ required: true, message: '请输入AppId', trigger: 'blur' }],
        appSecret: [{ required: true, message: '请输入appSecret', trigger: 'blur' }]
      },
      list: [],
      listLoading: true,
      selectRows: '',
      elementLoadingText: '正在加载...',
      page: {
        total: 0,
        size: 10,
        currentPage: 1
      },
      codeImg: '',
      dialogVisible: false,
      passw: 'password',
      icon: 'el-input__icon el-icon-view',
      data: '',
      form3: {
        version: '',
        describe: ''
      },
      plugin: [],
      shawCode: '1',
      initTimer: 60,
      times: 20,
      updateTimes: 60,
      code: 1,
      loginStatus: false,
      loginImg: '',
      previewImg: ''
    };
  },
  methods: {
    async getEdition() {
      const { data } = await getEdition();
      this.data = data;
    },
    async init() {
      if (this.activeName == '1') {
        this.bus.$emit('loading', true);
        this.formData();
      } else if (this.activeName == '2') {
        this.bus.$emit('loading', true);
        this.miniTemplates();
      } else if (this.activeName == '3') {
        this.fetchData();
      } else if (this.activeName == '4') {
        this.uploadData();
      }
    },
    async handleClick() {
      this.bus.$emit('loading', true);
      if (this.activeName == '1') {
        this.formData();
      } else if (this.activeName == '2') {
        this.miniTemplates();
      } else if (this.activeName == '3') {
        this.fetchData();
      } else if (this.activeName == '4') {
        this.uploadData();
      }
      this.getEdition();
      this.code = 1;
    },
    async formData() {
      const { data } = await getConfig({ ident: 'miniConfig' });
      this.form2 = this.form;
      this.form = Object.assign(this.form2, data);
      this.bus.$emit('loading', false);
    },
    async miniTemplates() {
      const { data } = await getConfig({ ident: 'miniTemplates' });
      // this.konobj = this.form
      this.form2Data = Object.assign({}, data);
      this.bus.$emit('loading', false);
    },
    async fetchData() {
      this.listLoading = true;
      const { data } = await getPage({ page: 'miniPage' });
      this.list = data;
      this.bus.$emit('loading', false);
      setTimeout(() => {
        this.listLoading = false;
      }, 100);
    },
    async uploadData() {
      this.shawCode = '1';
      const { data } = await getConfig({ ident: 'wxUpdateConfig' });
      this.plugin = data.plugin ? data.plugin : [];
      this.form3 = Object.assign({}, data);
      this.bus.$emit('loading', false);
    },
    handleCurrentChange(val) {
      this.page.currentPage = val;
      this.fetchData();
    },
    copyText(row) {
      let Url2 = row.page;
      var oInput = document.createElement('input');
      oInput.value = Url2;
      console.log(oInput.value);
      document.body.appendChild(oInput);
      oInput.select();
      document.execCommand('Copy');
      oInput.className = 'oInput';
      oInput.style.display = 'none';
      this.$message({
        message: '复制成功',
        type: 'success'
      });
    },
    async codeSee(row) {
      this.listLoading = true;
      const { data } = await getCode({ ident: row.ident, page: row.page });
      if (data) {
        this.codeImg = data;
      }
      this.listLoading = false;
      this.dialogVisible = true;
    },
    async yjdy() {
      const { msg } = await getMiniTemplates();
      this.$baseMessage(msg, 'success');
      this.init();
    },
    async onSubmit() {
      if (this.activeName == '1') {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            this.form.ident = 'miniConfig';
            this.form.identName = '微信小程序配置';
            const { msg } = await postConfig(this.form);
            this.$baseMessage(msg, 'success');
            this.init();
          } else {
            return false;
          }
        });
      } else if (this.activeName == '2') {
        this.$refs['form2Data'].validate(async (valid) => {
          if (valid) {
            this.form2Data.ident = 'miniTemplates';
            this.form2Data.identName = '订阅消息';
            const { msg } = await postConfig(this.form2Data);
            this.$baseMessage(msg, 'success');
            this.init();
          } else {
            return false;
          }
        });
      }
    },
    showPass() {
      if (this.passw == 'text') {
        this.passw = 'password';
        this.icon = 'el-input__icon el-icon-view';
      } else {
        this.passw = 'text';
        this.icon = 'el-input__icon el-icon-unlock';
      }
    },
    async upload() {
      if (this.form3.version == '') {
        this.$baseMessage('请填写版本号', 'warning');
        return;
      }
      if (this.form3.describe == '') {
        this.$baseMessage('请填写版本描述', 'warning');
        return;
      }
      // console.log(this.form3,this.plugin,this.checkList)
      // return
      const { data } = await postConfig({ ident: 'wxUpdateConfig', identName: '上传小程序', version: this.form3.version, describe: this.form3.describe, plugin: this.plugin });
      this.shawCode = '2';
      //登录码定时器
      if (this.code == '1') {
        this.initTimer = setInterval(() => {}, 5000);
        this.WxUpdate();
      } else {
        this.initTimer--;
      }
      this.loginTimer = setInterval(async () => {
        if (this.code == 2) {
          clearInterval(this.loginTimer);
          //登录状态定时器
          this.loginStatusTimer = setInterval(async () => {
            await this.GetLoginStatus();
            if (this.code == 3) {
              clearInterval(this.loginStatusTimer);
              //预览定时器
              this.Preview();
              this.updateTimer = setInterval(async () => {
                if (this.code == 4) {
                  clearInterval(this.updateTimer);
                } else {
                  this.updateTimes--;
                  if (this.updateTimes === 0) {
                    clearInterval(this.updateTimer);
                    this.$baseMessage('上传失败请重试', 'error');
                    this.uploadData();
                  }
                }
              }, 1000);
            } else {
              this.updateTimes--;
              if (this.updateTimes === 0) {
                clearInterval(this.loginStatusTimer);
                this.$baseMessage('上传失败请重试', 'error');
                this.uploadData();
              }
            }
          }, 3000);
        } else {
          this.times--;
          if (this.times === 0) {
            clearInterval(this.loginTimer);
            this.$baseMessage('上传失败请重试', 'error');
            this.uploadData();
          }
        }
      }, 1200);
    },
    async WxUpdate() {
      const { msg, data } = await getLoginCode();
      if (msg == '成功') {
        this.code = 2;
        this.loginImg = data;
      }
    },
    async GetLoginStatus() {
      const { msg, data } = await getLoginStatus();
      if (msg == '成功') {
        this.code = 3;
      }
    },
    async Preview() {
      const { msg, data } = await preview();
      var storeData = { id: this.id };
      if (msg == '成功') {
        this.code = 4;
        this.previewImg = data;
      } else {
        // this.$baseMessage(msg, "error");
        this.uploadData();
        this.$baseConfirm(
          msg,
          null,
          async () => {
            location.reload();
          },
          async () => {
            location.reload();
          }
        );
      }
    }
  }
};
</script>
<style  lang="scss" scoped>
.orderpop p {
  line-height: 24px;
}

.msgtext {
  text-indent: -60px;
  padding-left: 70px;
}
.imgCode {
  width: 200px;
  height: 200px;
}
.waitTime {
  font-size: 26px;
  margin-top: 10px;
  color: #2a75ed;
}
.loadWait {
  width: 32px;
  height: 32px;
}
.el-button.is-plain:focus,
.el-button.is-plain:hover {
  border-color: #155bd4;
  color: #fff;
}
</style>
